$(function () {
    var query = {}, fields = 'id|name|shortName|admin|address|showDriver|phone|fax|order|remark',
        $allow = $('.btn-allow'),
        $refuse = $('.btn-refuse'),
        $log = $('.btn-log'),
        $update = $('.btn-update'),
        $print = $('.btn-print'),
        $search = $('.search'),
        $export = $('.search-export'),
        $clear = $('.btn-clear-zero'),
        $delete = $('.btn-delete'),
        $hexiao = $('.btn-hexiao'), // 录入实体数量
        $updateBatch = $('.btn-update-batch'),
        $searchBar = $('.search-btn'), list = [];

    var config = {
            coloum_num: 8, //列数目
            query: '/ladingBill/query?',//分页查询URL,
            update: '/ladingBill/update',
            refuse: '/ladingBill/refuse',
            goods: '/goods/query?size=50',//分页查询URL,
            query_store: '/store/query?size=300',
            // update_labing_bill_actual: '/ladingBill/update',
            update_labing_bill_actual: '/ladingBill/update_labing_bill_actual',
            'delete': '/ladingBill/delete',
        },
        btns = [$refuse, $allow, $log, $print, $clear, $delete, $updateBatch, $hexiao];
    $searchBar.click(function () {
        $(this).button('loading');
        search({
            goodsId: $('[name=goodsId]').val(), page: 1,
            type: $('[name=type]').val(),
            storeId: $('[name=storeId]').val(),
            no: $('[name=no]').val(),
            storeName: $('[name=storeName]').val(),
            clienteleName: $('[name=clienteleName]').val(),
        });
    });
    $('[name=clienteleName]').on('keypress', function (e) {
        if (e.keyCode == 13) {
            $searchBar.click();
        }
    });
    $('[name=storeName]').on('keypress', function (e) {
        if (e.keyCode == 13) {
            $searchBar.click();
        }
    });
    $('[name=no]').on('keypress', function (e) {
        if (e.keyCode == 13) {
            $searchBar.click();
        }
    });

    $.get(config.query_store, function (data) {
        if (data.code == 200) {
            list = data.list;
        }
    });
    $('[name=type]').change(function () {
        search({
            goodsId: $('[name=goodsId]').val(), page: 1,
            type: $('[name=type]').val(),
            storeId: $('[name=storeId]').val(),
            no: $('[name=no]').val(),
            storeName: $('[name=storeName]').val(),
            clienteleName: $('[name=clienteleName]').val(),
        })
    });
    $('[name=storeId]').change(function () {
        search({
            goodsId: $('[name=goodsId]').val(), page: 1,
            type: $('[name=type]').val(),
            storeId: $('[name=storeId]').val(),
            no: $('[name=no]').val(),
            storeName: $('[name=storeName]').val(),
            clienteleName: $('[name=clienteleName]').val(),
        })
    });
    $('[name=goodsId]').change(function () {
        search({
            goodsId: $('[name=goodsId]').val(), page: 1,
            type: $('[name=type]').val(),
            storeId: $('[name=storeId]').val(),
            no: $('[name=no]').val(),
            storeName: $('[name=storeName]').val(),
            clienteleName: $('[name=clienteleName]').val(),
        })
    });
    $.when(parent.window.getDataByUrl(config.goods, "goods"))
        .then(function (goods) {
            goods.map(function (item) {
                $('[name=goodsId]').append('<option value="' + item.id + '">' + item.name + '</option>')
            });
            $('[name=goodsId]').selectpicker({liveSearch: true,});
        });
    function search(obj, isForce, isExport) {
        var query_ = {
            startDate: $('[name=startDate]').val(),
            endDate: $('[name=endDate]').val(),
        };
        query_ = $.extend({}, query, query_, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                $searchBar.button('reset');
                return $loading.fadeOut();
            }
        }
        var arg = [];
        Object.keys(query_).map(function (key) {
            if (query_[key] != '') {
                arg.push(key + '=' + query_[key])
            }
        });
        query = query_;
        query.timestamp = Date.now();
        if (isExport) {
            return config.query + arg.join('&');
        }
        $.get(config.query + ajaxArgStrGenerator(query), function (res) {
            var _$table = $('.table-responsive .table');
            destroyBtn();
            _$table.$Table2($.extend(TABLE_SETTING, {
                destroyBtn: destroyBtn, //禁用按钮
                createBtn: createBtn, // 启用她扭
                search: search,
                export: true, //
                showSearchComplex: true, //显示复杂搜索框
                complexItems: [
                    {label: "", name: 'date', dateRange: true},
                ],
                fields: [
                    {name: 'no', _sort: 'no', label: '提单号', enableSearch: true, combine: true},
                    {name: 'carId', _sort: 'no', label: '车号(收货公司)', enableSearch: true, combine: true},
                    {name: 'goodsName', label: '产品名称', combine: true},
                    {
                        name: 'checkStatus', style:"padding:3px;", label: '审核状态', combine: true, filter: function (item) {
                        return tfCheckStatus(item.checkStatus);
                    }
                    },
                    {name: 'price', label: '单价'},
                    {
                        name: 'total', label: '金额', filter: function (item) {
                        return floatTool.multiply(item.numberThisTime, item.price);
                    }
                    },
                    {
                        name: 'type', label: '提单类型', combine: true,
                        enableFilter: true,
                        filters: [
                            {label: '全部', value: ''},
                            {label: '车号', value: 0},
                            {label: '转货权', value: 1},
                            {label: '介绍信', value: 2}],
                        filter: function (item) {
                            return tfLadingBillType(item.type);
                        }
                    },
                    {
                        name: 'expireTime', label: '提单有效期', combine: true, filter: function (item) {
                        return formatDate(item.expireTime);
                    }
                    },
                    {name: 'numberThisTime', label: '提货数量'},
                    {name: 'actual', label: '实提数量'},
                    {name: 'storeName', label: "提货仓库", enableSearch: true, combine: true},
                    {name: 'clienteleName', label: "客户名称", combine: true, enableSearch: true,},
                    {name: 'checker', label: "操作员", combine: true},
                ],
                data: formatListsData(res.list, 'id') || [],
            }));
            var page = res.page;
            pageInit(page, query, search);
        });
    }

    onClick($clear, function () {
        var $json = $(this).data('json');
        if (confirm("确定实提清零?")) {
            $.get('/ladingBill/clear/' + $json.id, function (res) {
                if (res.code == 200) {
                    fnSuccess("清零成功!");
                    search({}, true);
                } else {
                    fnFail(res.error || "清零失败!");
                }
            })
        }
    });
    onClick($hexiao, function () {
        var $json = $(this).data('json');//
        var $actual = parseInt($json.actual);
        if ($actual) {
            return alert('实体数已录入!');
        }
        $.get('/ladingBill/get?id=' + $json.id, function (res) {
            if (res.code == 200) {
                var $modal = _alert({
                    title: '录入实提数量',
                    width: '95%',
                    body: ejs.render($('#detail').html(), res.data),
                    shown: function () {
                        onInput($('[name=actuals]'), function () {
                            if (parseFloat($(this).val()) > parseFloat($(this).data('max'))) {
                                $(this).val($(this).data('max'));
                            }
                        });
                        $('#instore-form').formValidation('destroy').formValidation($.extend({}, VALIDATION_SETTING, {
                            fields: {
                                actuals: {
                                    row: '.td',
                                    validators: {
                                        notEmpty: {
                                            message: '实提数量必填'
                                        },
                                    }
                                },
                            }
                        }))
                            .off('success.form.fv').on('success.form.fv', function (e) {
                            e.preventDefault();
                            var validate = false, total = 0;
                            $('input[type=text][name=actuals]').each(function (index, item) {
                                total += parseFloat($(item).val());
                                if (parseFloat($(item).data('max')) < parseFloat($(item).val())) {
                                    validate = true;
                                }
                            });
                            if (validate) {
                                return alert('实提数量不能大于对应提单数量!')
                            }
                            if (total == 0) {
                                return alert("入库合计不能为零!");
                            }
                            var form = parseSearch($(e.target).serialize());
                            $.post("/ladingBill/batchUpdateLadingBillActual", form, function (xhr, data) {
                                if (xhr.code == 200) {
                                    fnSuccess('操作成功!');
                                    search({}, true);
                                    $modal && $modal.modal('hide');
                                } else {
                                    alert(xhr.error || xhr.msg);
                                }
                            });
                        });
                        //
                    }
                })
            }
        })

    })
    onClick($updateBatch, function () {
        var $json = $(this).data('json');
        window.location.href = './send.html?id=' + $json.id;
    });

    onClick($delete, function (item) {
        var $json = $(this).data('json');
        if (confirm("确定删除提货单?")) {
            $.get('/ladingBill/delete/' + $json.id, function (res) {
                if (res.code == 0) {
                    fnSuccess("删除成功!");
                    search({}, true);
                } else {
                    fnFail(res.error || "删除失败!");
                }
            })
        }
    });

    onClick($update, function () { // 提单变更
        var $current = $(this).data('json');
        parent.window.open('http://' + window.location.hostname + '/admin/store/express/print/index.html?action=change&id=' + $current.id + '&type=' + $current.type + '&clienteleName=' + $current.clienteleName + '&storeName=' + $current.storeName, '_blank');
    });
    onClick($log, function () {
        var $current = $(this).data('json');
        window.location = './../../log/log.html?id=' + $current.id + '&type=ladingBill';
    });
    onClick($print, function () {
        var $current = $(this).data('json');
        parent.window.open('http://' + window.location.hostname + '/admin/store/express/print/index.html?id=' + $current.id + '&type=' + $current.type + '&clienteleName=' + $current.clienteleName + '&storeName=' + $current.storeName, '_blank');
    });
    onClick($allow, function () {
        var $current = $(this).data('json');
        window.location = ' ./check.html?id=' + $current.id + '&goodsId=' + $current.goodsId;
    });
    onClick($refuse, function () {
        var $current = $(this).data('json');
        var reason = prompt("原因：");
        if (reason) {
            $.post(config.refuse
                , {
                    id: $current.id,
                    reason: reason
                }, function (data) {
                    if (data.code == 200) {
                        fnSuccess("操作成功");
                        search({}, true);
                    } else {
                        fnFail(data.error || "操作失败");
                    }
                })
        }
    });
    function destroyBtn() {
        btns.forEach(function (item) {
            item.data('json', null);
            disableBtn(item);
        });
    }

    function createBtn(_this) {
        destroyBtn();
        var $data = $(_this).data('json');
        if ($data.checkStatus == 0) {
            enableBtn($allow, $data);
            enableBtn($refuse, $data);
        } else if ($data.checkStatus == 1) {
            enableBtn($print, $data);
            if ($data.actual > 0) {
                enableBtn($clear, $data);
            }
            if ($data.actual == 0) {
                enableBtn($updateBatch, $data);
                enableBtn($delete, $data);
                enableBtn($hexiao, $data);
            }
        }
        enableBtn($log, $data);

    }

    onClick($export, function () {
        generateExportUrl(search({}, true, true));
    });
    $('.lading-bill-check-edit').click(function () {
        if ($(this).html().indexOf("编辑") > -1) {
            $(this).html("保存");
            $('.create-lading-bill input').attr('disabled', false);
            $('.create-lading-bill [name=numberThisTime]').attr('disabled', true);
        } else {
            var json = $(this).data('json');
            var form = {
                id: json.id,
                type: $('.lading-bill-check-edit').closest('.create-lading-bill').find('[name=type]:checked').val(),
                carId: $('.lading-bill-check-edit').closest('.create-lading-bill').find('[name=carId]').val(),
                driver: $('.lading-bill-check-edit').closest('.create-lading-bill').find('[name=driver]').val(),
                driverPhone: $('.lading-bill-check-edit').closest('.create-lading-bill').find('[name=driverPhone]').val(),
                expireTime: $('.lading-bill-check-edit').closest('.create-lading-bill').find('[name=expireTime]').val(),
                storeId: $('.lading-bill-check-edit').closest('.create-lading-bill').find('[name=deliverPlace]').data('id'),
            };
            $.post('/ladingBill/update', form, function (xhr) {
                if (xhr.code == 200) {
                    alert("保存成功!");
                    search({}, true);
                } else {
                    alert(xhr.error);
                }
            })
        }
    });
    $('.lading-bill-confirm').on('show', function (event) {
        var button = $(event.relatedTarget);
        var recipient = button.data('json');
        var modal = $(this);
        if (recipient) {
            $('.lading-bill-check-edit').data("json", recipient);
            $('.lading-bill-check-edit').closest(".modal-dialog").find('input').attr('disabled', true);
            $('.lading-bill-check-edit').html('编辑');
            $('.lading-bill-confirm input[name=type][value=' + recipient.type + ']').attr('checked', true);
            $('.lading-bill-confirm input[name=carId]').val(recipient.carId);
            $('.lading-bill-confirm input[name=driver]').val(recipient.driver);
            $('.lading-bill-confirm input[name=driverPhone]').val(recipient.driverPhone);
            $('.lading-bill-confirm input[name=numberThisTime]').val(recipient.numberThisTime);
            $('.lading-bill-confirm input[name=expireTime]').val(moment(recipient.expireTime).format('YYYY-MM-DD'));
            // storeId
            $('.lading-bill-confirm input[name=deliverPlace]').val(recipient.deliverPlace);
            $("[name=expireTime]").datepicker({
                todayHighlight: true,
            });
            //debugger;
            // $.get('/offer/getByOrderId?id=' + recipient.orderId, function (dataOffer) {
            // var _$item = dataOffer.data;
            // if (_$item.deliverPlaceIds && _$item.deliverPlace && (_$item.deliverPlace.split(',').length >= _$item.deliverPlaceIds.split(',').length)) {
            //     list.map(function (item) {
            //         if ((',' + _$item.deliverPlaceIds + ',').indexOf(',' + item.id + ',') == -1) {
            //             $('.stores_area').append('<label class="radio-inline" style="margin: 0;padding-right: 15px;"> \
            // <input type="radio"  name="storeId" value="' + item.id + '" data-value="' + item.name + '"> ' + item.name + ' \
            // </label>')
            //         }
            //         if (recipient.storeId == item.id) {
            //             $('.lading-bill-confirm input[name=deliverPlace]').val(item.name);
            //             $('.lading-bill-confirm input[name=deliverPlace]').data('id', item.id);
            //         }
            //     })
            // }
            // $('.stores').html('');
            // if (_$item.deliverPlaceIds) {
            //     _$item.deliverPlaceIds.split(',').map(function (item, index) {
            //         if (_$item.deliverPlace.split(',')[index]) {
            //             $('.stores').append('<label class="radio-inline" style="margin: 0;padding-right: 15px;"> \
            // <input type="radio"  name="storeId" value="' + item + '" data-value="' + _$item.deliverPlace.split(',')[index] + '"> ' + _$item.deliverPlace.split(',')[index] + ' \
            // </label>');
            //         }
            //     });
            // }
            //     $('[name=storeId]').focus(function (e) {
            //         $('[name=deliverPlace]').val($(this).data('value'));
            //         $('[name=deliverPlace]').data('id', $(this).val());
            //         $(this).closest('.select_multi').fadeOut();
            //     });
            // });
        }

        modal.find('.modal-title').text('审核订单');
        modal.find('.modal-title').data('id', recipient);
    }).on('okHide', function (event) {
        var $id = $(event.target).closest('.modal-content').find('.modal-title').data('id');
        if ($(event.target).text().indexOf('通过') > -1) {
        }
        return false;
    });
    search({}, true);

    // 表单提交
    var $submit = $('#submit');
    $submit.on('click', function () {
        var $btn = $(this).button('loading');
    });
    $(".create-lading-bill").validate({
        submitHandler: function (form_) {
            var $json = $('.lading-bill-check-edit').data('json');
            $.post(config.update, {
                id: $json.id,
                checkStatus: 1,
            }, function (data) {
                if (data.code == 200) {
                    search({}, true);
                    $('.lading-bill-confirm').modal('hide');
                } else {
                    alert(data.error)
                }
            });
            return false;
        }
    });
});